<?php

namespace app\adminapi\controller\v2;

use app\adminapi\controller\AuthController;
use app\model\basic\Parameter;
use think\exception\ValidateException;
use think\Request;

class Params extends AuthController
{
    public function list(Request $request)
    {
        $page = $request->param('page',1);
        $limit = $request->param('size',10);
        $where = [];
        $name = $request->param('para_name', '');
        if ($name) {
            $where[] = ['para_name', 'like', '%'.$name.'%'];
        }
        $type = $request->param('type', '');
        if ($type) {
            $where[] = ['type', '=', $type];
        }

        $data = Parameter::where('status', 1)
            ->where($where)
            ->order('id desc')
            ->paginate($limit);

        return app('json')->success([
            'total' => $data->total(),
            'list' => $data->items(),
        ]);
    }

    public function info(Request $request)
    {
        $id = $request->param('id',0);
        $data = Parameter::where('id', $id)
            ->where('status', 1)
            ->find();
        return app('json')->success([
            'data' => $data
        ]);
    }

    public function save(Request $request)
    {
        $params = $request->only([
            'para_name', 'type'
        ]);
        $id = input('id', '');
        try {
            validate([
                'para_name|名称' => 'require|max:50',
                'type|类型' => 'require'
            ])->check($params);
        } catch (validateException $e) {
            return app('json')->fail($e->getError());
        }
        if ($id) {
            $exists = Parameter::where('status', 1)
                ->where('id', '<>', $id)
                ->where('para_name', $params['para_name'])
                ->find();
            if ($exists) {
                return app('json')->fail('参数名称已存在');
            }
            Parameter::update($params, ['id' => $id]);
        } else {
            $exists = Parameter::where('status', 1)
                ->where('para_name', $params['para_name'])
                ->find();
            if ($exists) {
                return app('json')->fail('参数名称已存在');
            }
            Parameter::create($params);
        }
        return app('json')->success();
    }

    public function delete(Request $request)
    {
        $id = $request->param('id',0);
        $res = Parameter::where('id', $id)
            ->update(['status' => 0]);

        return app('json')->success();
    }
}